#include <etcd/Client.hpp>
#include <etcd/KeepAlive.hpp>
#include <etcd/Response.hpp>
#include <etcd/Value.hpp>
#include <etcd/Watcher.hpp>
#include <iostream>
#include <thread>

void callback(const etcd::Response& resp)
{
    if(!resp.is_ok()) {
        std::cout << "错误的事件通知: " << resp.error_message() << '\n';
       return;
    } 
    for(const auto& ev : resp.events()) {
        if(ev.event_type() == etcd::Event::EventType::PUT) {
            std::cout << "服务信息发送改变: \n";
            std::cout << "当前的值: " << ev.kv().key() << " -- " << ev.kv().as_string() << '\n';
            std::cout << "原来的值: " << ev.prev_kv().key() << " -- " << ev.prev_kv().as_string() << '\n';
        } else if(ev.event_type() == etcd::Event::EventType::DELETE_) {
            std::cout << "服务信息下线被删除: \n";
            std::cout << "当前的值: " << ev.kv().key() << " -- " << ev.kv().as_string() << '\n';
            std::cout << "原来的值: " << ev.prev_kv().key() << " -- " << ev.prev_kv().as_string() << '\n';
        } else {
            std::cout << "错误的事件通知类型: \n";
        }
    }
} 

int main()
{
    std::string etcd_host = "http://127.0.0.1:2379";
    etcd::Client client(etcd_host);

    // 获取键值对数据(获取 service 所有的键值对)
    etcd::Response resp = client.ls("/service").get();
    if(!resp.is_ok()) {
        std::cout << "获取数据失败: " << resp.error_message() << '\n';
       return 1;
    } 
    for (int i = 0; i < resp.keys().size(); ++i) {
        std::cout << resp.value(i).as_string() << " 可以提供 " << resp.key(i) << " 服务\n";
    }
    // true: 递归监控 service 所有目录下的数据改变
    etcd::Watcher watcher(client, "/service", callback, true);
    watcher.Wait();
    return 0; 
}